//
//  ReleaseController.m
//  XuPei
//
//  Created by 古智性 on 15/7/19.
//  Copyright (c) 2015年 BenHu. All rights reserved.
//

#import "ReleaseController.h"
#import "Header.h"
#import "UzysAssetsPickerController.h"
#import "Masonry.h"

@implementation ZYLabel

@synthesize hcId;
@synthesize type;
@end

@interface ReleaseController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UITableViewDelegate,UITableViewDataSource>
{
    UILabel *placeText;
    UIButton *imgBtn;
    NSMutableArray *_imgArray;
    UIImageView *addImage;
    UIView *view;
    BOOL isok;
}
@end

@implementation ReleaseController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor=[UIColor lightGrayColor];
    self.title=@"发布动态";
    
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    
    _imgArray = [[NSMutableArray alloc]initWithCapacity:0];
    ;
    self.mytableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH-114) style:UITableViewStylePlain];
    
    self.mytableview.dataSource = self;
    
    self.mytableview.delegate = self;
    
    //    self.mytableview.backgroundColor=[UIColor redColor];
    self.mytableview.backgroundColor = [UIColor whiteColor];
    
    self.mytableview.separatorColor = [UIColor clearColor];
    [self.view addSubview:self.mytableview];
    
    
    yiYuanMingZi = [[ZYLabel alloc]initWithFrame:CGRectMake(kScreenW/2+40, 0, kScreenW/2-90, 40)];

    yiYuanMingZi.font=[UIFont systemFontOfSize:12];
    
    yiYuanMingZi.textColor=[UIColor whiteColor];
    
    yiYuanMingZi.textAlignment=NSTextAlignmentRight;
    
    UIBarButtonItem*ba=[[UIBarButtonItem alloc]initWithCustomView:yiYuanMingZi];
    
    UIButton*btn=[[UIButton alloc]initWithFrame:CGRectMake(yiYuanMingZi.frame.origin.x+yiYuanMingZi.frame.size.width+5, 10, 15, 7)];
    
    [btn setBackgroundImage:[UIImage imageNamed:@"10"] forState:UIControlStateNormal];
    
    
    [btn addTarget:self action:@selector(XuanZeYiYuan) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * bar = [[UIBarButtonItem alloc]initWithCustomView:btn];
    
    self.navigationItem.rightBarButtonItems=@[bar,ba];
    
    caiDanTableView = [[UITableView alloc]initWithFrame:CGRectMake(2, 0, kScreenW-4, 250) style:UITableViewStyleGrouped];
    
    caiDanTableView.layer.borderWidth=.7f;
    
    caiDanTableView.delegate = self;
    
    caiDanTableView.dataSource =self;
    
    caiDanTableView.tag= 100;
    
    caiDanTableView.hidden=YES;
    
    [self.view addSubview:caiDanTableView];


    yiYuanMingZi.text = [[[self.hospitalCommunityArr valueForKey:@"hospitals"] objectAtIndex:0] valueForKey:@"name"];
    yiYuanMingZi.hcId = [[[[self.hospitalCommunityArr valueForKey:@"hospitals"] objectAtIndex:0] valueForKey:@"id"] longValue];
    
    yiYuanMingZi.type = 1;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton * faBuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    faBuBtn.frame = CGRectMake(0, kScreenH-104, kScreenW, 40);
    
    faBuBtn.backgroundColor = CL_00cc85;
    
    [faBuBtn setTintColor:[UIColor whiteColor]];
    
    [faBuBtn setTitle:@"发    布" forState:UIControlStateNormal];
    
    [faBuBtn addTarget:self action:@selector(FaBu) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:faBuBtn];
    
}


#pragma UITableViewDataSource and delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 100) {
        
        return 40;
    }
    
    if (indexPath.section==1 && indexPath.row==0)
    {
        return 100+(_imgArray.count/4)*80;
    }
    return 40;
}

//区头
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 100) {
        
        return 40;
    }

    
    if (section==0)
    {
        return kScreenH/4;
    }
    else
    {
        return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 100) {
        
        return 2;
    }

    
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag ==100) {
        
        if (!flag[section])
        {
            
            NSArray *arr =[self.hospitalCommunityArr valueForKey:section==0?@"hospitals":@"communitys"];
            
            return arr.count;
            
        }
        else
        {
            return 0;
        }

    }
    if (section==0)
    {
        return 0;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 100) {
        
        
        static NSString * tab=@"";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tab];
        if (!cell) {
            
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tab];
            
        }
        
        
        if (indexPath.section==0)
        {
            
            cell.textLabel.text = [[[ self.hospitalCommunityArr valueForKey:@"hospitals"] objectAtIndex:indexPath.row] valueForKey:@"name"];
            
        }
        else{
            cell.textLabel.text = [[[ self.hospitalCommunityArr valueForKey:@"communitys"] objectAtIndex:indexPath.row] valueForKey:@"name"];
        }
        
        return cell;

    }
    if (indexPath.section==0)
    {
        return nil;
    }
    else
    {
    static NSString *cellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;

    for (int i=1000; i<1010;i++)
    {
        UIButton *btn=(UIButton *)[cell viewWithTag:i];
        [btn removeFromSuperview];
    }
    
    CGFloat w_w=(kScreenW-40-60*4)/3.0; //两个图片左右间距
    for (int i=0; i<[_imgArray count]+1;i++)
    {
        if (i==_imgArray.count)
        {
            
            UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
            button.tag=i+1000;
            [button setBackgroundImage:[UIImage imageNamed:@"jia.png"] forState:UIControlStateNormal];
            [cell addSubview:button];
            [button addTarget:self action:@selector(phtotButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            button.frame=CGRectMake(20+i%4*(60+w_w),20+i/4*(60+20), 60, 60);
            
            }
        else
        {
//            NSString  *imageurl=[_imgArray objectAtIndex:i];
            UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
            button.tag=i+1000;
            [button setImage:[_imgArray objectAtIndex:i] forState:UIControlStateNormal];
            button.frame=CGRectMake(20+i%4*(60+w_w),20+i/4*(60+20), 60, 60);
            [cell addSubview:button];
            [button addTarget:self action:@selector(phtotButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(photoDeleteClick:)];
            longPress.minimumPressDuration = 1;
            [button addGestureRecognizer:longPress];
            

        }
    }

    return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 100)
    {
        
        yiYuanMingZi.text = [[[self.hospitalCommunityArr valueForKey:indexPath.section==0?@"hospitals":@"communitys"] objectAtIndex:indexPath.row] valueForKey:@"name"];
        yiYuanMingZi.hcId = [[[[self.hospitalCommunityArr valueForKey:indexPath.section==0?@"hospitals":@"communitys"] objectAtIndex:indexPath.row] valueForKey:@"id"] longValue];
        
        yiYuanMingZi.type =(int)indexPath.section + 1;
        
        
//        NSLog(@"----%@----%ld-----%d",yiYuanMingZi.text,yiYuanMingZi.hcId,yiYuanMingZi.type);
        isOK = NO;
        caiDanTableView.hidden = YES;
        
    }
    
  
    if (indexPath.section==1)
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        [self.view endEditing:YES];
        
        [UIView animateWithDuration:0.3  animations:^{
            self.mytableview.frame=CGRectMake(0, 0, kScreenW, [UIScreen mainScreen].bounds.size.height-44);
        }];
    }
   
    
}

#pragma uitextViewDelegate 控制键盘弹出时让输入框滚动到合适的位置

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.3  animations:^{
        self.mytableview.frame=CGRectMake(0, 0, kScreenW, [UIScreen mainScreen].bounds.size.height-44-20);
    }];
}
-(void)phtotButtonClick:(UIButton *)send
{
    if (send.tag<1000+_imgArray.count)
    {
    }
    
    
    if (send.tag== 1000+_imgArray.count)
    {
        if (_imgArray.count>=9)
        { [[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"最多选择9张图片" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil]show];
            
        }
        else
        {
            self.addOrModefy=10;
            [self.view endEditing:YES];
            [UIView animateWithDuration:0.3  animations:^{
                self.mytableview.frame=CGRectMake(0, 0, kScreenW, self.mytableview.frame.size.height);
            }];
            
            UIActionSheet *sheet;
            // 判断是否支持相机
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                sheet  = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
            }
            else {
                sheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"从相册选取" otherButtonTitles:@"拍摄", nil];
            }
            sheet.tag = 255;
            [sheet showInView:self.view];
        }
    }
}

#pragma 添加图片相关的一些代理方法 相册或照片
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255)
    {
        
        NSUInteger sourceType = 0;
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            
            switch (buttonIndex)
            {
                case 0:
                {   // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                    imagePickerController.allowsEditing =YES;
                    imagePickerController.sourceType = sourceType;
                    imagePickerController.delegate = self;
                    [self presentViewController:imagePickerController animated:YES completion:^{
                        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
                    }];

                }
                    break;
                case 1:
                    // 相册
                {
                    
                    UzysAssetsPickerController *picker = [[UzysAssetsPickerController alloc] init];
                    picker.delegate = self;
                    picker.maximumNumberOfSelectionPhoto = 9;
                    [self presentViewController:picker animated:YES completion:^{
                        
                    }];

                    
                }
                    break;
                    
                case 2:
                    // 取消
                    return;
                    break;
            }
        }
        else
        {
            if (buttonIndex == 0)
            {
                UzysAssetsPickerController *picker = [[UzysAssetsPickerController alloc] init];
                picker.delegate = self;
                picker.maximumNumberOfSelectionPhoto = 9;
                [self presentViewController:picker animated:YES completion:^{
                    
                }];
                

                
            }
            else
            {
                return;
            }
        }
        // 跳转到相机或相册页面
        
    }
}
- (void)UzysAssetsPickerController:(UzysAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
   
    
    if([[assets[0] valueForProperty:@"ALAssetPropertyType"] isEqualToString:@"ALAssetTypePhoto"]) //Photo
    {
        [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            ALAsset *representation = obj;
            
            UIImage *image = [UIImage imageWithCGImage:representation.defaultRepresentation.fullResolutionImage
                                               scale:representation.defaultRepresentation.scale
                                         orientation:(UIImageOrientation)representation.defaultRepresentation.orientation];
            
            if (_imgArray.count <9)
            {
                [_imgArray addObject:image];

                
                
            }
            else{
                
               *stop=YES;
                
                [[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"最多选择9张图片" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil]show];
                
            }
         
    
        }];
        [self.mytableview reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
        

        
    }

    
}
// button 的长按 删除图片
-(void)photoDeleteClick:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state==UIGestureRecognizerStateBegan)
    {
        UIButton *send=(UIButton *)gestureRecognizer.view;
        self.addOrModefy=(int)send.tag-1000;
        UIAlertView *ale=[[UIAlertView alloc]initWithTitle:@"提示" message:@"确定删除这张图片吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        ale.tag=56;
        [ale show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==56 && buttonIndex==1)
    {
        [_imgArray removeObjectAtIndex:self.addOrModefy];
        [self.mytableview reloadData];
    }
    
    if (alertView.tag==3010 || alertView.tag==3011 || alertView.tag==3012)
    {
        if (buttonIndex==1)
        {
            if(self.navigationController.viewControllers.count > 1)
            {
                // 当是Push进来的页面，用pop的方法弹出
                [self.navigationController popViewControllerAnimated:YES];
            }
            else if (self.presentingViewController) {
                // 当是present进来的页面，用dismiss的方法来关闭
                [self dismissViewControllerAnimated:YES completion:^(void){ }];
            }
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:^{
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }];

    UIImage * newImage= [self imageWithImageSimple:image scaledToSize:CGSizeMake(kScreenW, 200)];
    
    [_imgArray addObject:newImage];

   [self.mytableview reloadData];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 100)
    {
        UIView * view1=nil;
        
        view1 = [[UIView alloc]initWithFrame:CGRectMake(2, 0, kScreenW-4, 40)];
        
        view1.backgroundColor =CL_00cc85;
        
        UIButton * button=nil;
        button =[UIButton buttonWithType:UIButtonTypeCustom];
        
        [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
        UIImageView * imageView=nil;
        
        imageView = [[UIImageView alloc]init];
        
        imageView.image = [UIImage imageNamed:@"jiaoge"];
        if (section==0) {
            
            [button setTitle:@"医院分享" forState:UIControlStateNormal];
            button.tag=0;
        }
        else{
            
            [button setTitle:@"社区分享" forState:UIControlStateNormal];
            button.tag=1;
        }
        
        [button addTarget:self action:@selector(btnClock:) forControlEvents:UIControlEventTouchUpInside];
        
        [view1 addSubview:button];
        [view1 addSubview:imageView];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(view1).with.offset(10);
            make.size.mas_equalTo(CGSizeMake(60, 40));
            
        }];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            
            make.right.equalTo(button).with.offset(10);
            make.top.equalTo(view1).with.offset(15);
            make.size.mas_equalTo(CGSizeMake(8, 8));
            
        }];
        
        if (flag[section]) {
            
            imageView.transform = CGAffineTransformMakeRotation(180*M_PI/180);
            
        }
        else{
            imageView.transform = CGAffineTransformMakeRotation(0);
        }
        
        return view1;
        

        
    }
    
    if (section==0)
    {
        UIView *heardView=nil;
        heardView=[[UIView alloc]initWithFrame:CGRectMake(2, 2, kScreenW-4,kScreenH/4)];
        //        heardView.backgroundColor=[UIColor redColor];
        
        UITextView * textView = [[UITextView alloc]initWithFrame:CGRectMake(4,4,kScreenW-8, kScreenH/4)];
        textView.textAlignment = 0;
        textView.delegate = self;
        textView.tag = 110;
        textView.font = [UIFont systemFontOfSize:15];
        textView.pagingEnabled=YES;
        //返回按键的类型
        textView.returnKeyType = UIReturnKeyDefault;
        //给图层添加边框
        textView.layer.borderWidth = 0.5;
        //给图层添加边框
        textView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:0.5] CGColor];
        //获取焦点
//        [textView becomeFirstResponder];
        //重点属性
        self.modalPresentationCapturesStatusBarAppearance = NO;
        //重点属性
        //    self.edgesForExtendedLayout = UIRectEdgeNone;
        //重点属性
        self.extendedLayoutIncludesOpaqueBars = NO;
        [heardView addSubview:textView];
        
        
        placeText=[[UILabel alloc]initWithFrame:CGRectMake(4,0,200,30)];
        placeText.text=@"请填写详细信息";
        placeText.enabled = NO;
        placeText.font =  [UIFont systemFontOfSize:14];
        placeText.textColor = [UIColor lightGrayColor];
        [textView addSubview:placeText];
        
        return heardView;

    }
    if (section==1)
    {
     
        return nil;
    }
    return nil;
}
-(void)textViewDidChange:(UITextView *)textView  {
    if (textView.text.length==0)
    {
        placeText.text = @"请填写详细信息";
    }
    else{
        placeText.text=@"";
    }
    
}
#pragma mark---发布
-(void)FaBu{
  
    MBProgressHUD * hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    
    UITextView * textView = (UITextView *)[[[self.mytableview superview] superview] viewWithTag:110];
    
    if ([textView .text isEqualToString:@""]||textView == nil) {
        
        hud.mode = MBProgressHUDModeText;
        
        
        hud.labelText = @"写点什么吧";
        
        [hud hide:YES afterDelay:2];
        
        return;
    }
    
    hud.labelText =@"发布中...";
    
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
    
    //用户的id
    [dic setObject:@(1) forKey:@"userId"];
    
    [dic setObject:@(yiYuanMingZi.hcId) forKey:@"hcId"];
    
    
     [dic setObject: textView.text forKey:@"info"];
    [dic setObject:yiYuanMingZi.text forKey:@"hcName"];
;
    
    [QingQiuShuJu FaBuFenXiang:dic imagView:_imgArray HuiChuan:^(NSMutableArray *arr, BOOL isOK2)
    {
        if (isOK2)
        {
            hud.removeFromSuperViewOnHide = YES;
            
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];
            
            
            hud.mode = MBProgressHUDModeCustomView;
            
            hud.labelText = @"发布成功";
            
            [hud show:YES];
            [hud hide:YES afterDelay:3];
        }
        else{
            
            hud.mode = MBProgressHUDModeText;
            
            hud.labelText = @"网络连接错误";
            
            [hud show:YES];
            [hud hide:YES afterDelay:2];
            
        }
        
    }];
    
}
-(void)XuanZeYiYuan{
    
    if (!isOK) {
        caiDanTableView.hidden=NO;
    }
    
    else{
        
        caiDanTableView.hidden=YES;
    }
    isOK = !isOK;
}
- (void)btnClock:(UIButton *)sender{
    
    flag[sender.tag] = ! flag[sender.tag];
    
    
    
    [caiDanTableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationFade];
    
}

-(void)backBtnClick
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)dealloc{
    
    NSLog(@"销毁");
}
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
@end
//cocoapods 依赖管理，主要来管理第三方库；
